#include <boost/test/unit_test.hpp>
#include <logger/Log.h>


BOOST_AUTO_TEST_CASE(test_constructor)
{
	using namespace logger;

	std::ostringstream oss;

	LogOption option;
	option.priority = logger::kDebug | logger::kInfo | logger::kError;
	option.logger_ptr = LoggerPtr(new logger::OStreamLogger(oss));
	option.formatter_ptr = FormatterPtr(new StringFormatter("[%D] [%T] [%P] %M"));
	option.start_on_create = true;
	option.queue_timeout = 1;

	int result = 0;
	result = get_log_dispatcher().add("testlog", option);
	BOOST_CHECK(result == 0);

	LogOption tmp_option;
	result = get_log_dispatcher().get_option("testlog", tmp_option);

	BOOST_CHECK(result == 0);
	BOOST_CHECK(tmp_option.priority == option.priority);

	get_log_dispatcher().clear();
}

BOOST_AUTO_TEST_CASE(test_logging_message)
{
	using namespace logger;

	static std::ostringstream oss;

	LogOption option;
	option.priority = logger::kDebug | logger::kInfo | logger::kError;
	option.logger_ptr = LoggerPtr(new logger::OStreamLogger(oss));
	option.formatter_ptr = FormatterPtr(new StringFormatter("%M"));
	option.start_on_create = true;
	option.queue_timeout = 1;

	int result = get_log_dispatcher().add("testlog", option);
	BOOST_CHECK(result == 0);

	CLOGS(kDebug) << "test message";

	// the log is asnyc write to the stream
	sleep(1);
	BOOST_CHECK(oss.str() == "test message\n");

	oss.str("");
	CLOGF(kInfo, "test message %s %d", "test", 1);

	// the log is asnyc write to the stream
	sleep(1);
	BOOST_CHECK(oss.str() == "test message test 1\n");

	get_log_dispatcher().clear();
}


BOOST_AUTO_TEST_CASE(test_priority_change)
{
	using namespace logger;

	static std::ostringstream oss;

	LogOption option;
	option.priority = logger::kDebug;
	option.logger_ptr = LoggerPtr(new logger::OStreamLogger(oss));
	option.formatter_ptr = FormatterPtr(new StringFormatter("%M"));
	option.start_on_create = true;
	option.queue_timeout = 1;

	int result = get_log_dispatcher().add("testlog", option);
	BOOST_CHECK(result == 0);

	// this log should be filtered
	CLOGS(kError) << "test message";
	// the log is asnyc write to the stream
	sleep(1);
	BOOST_CHECK(oss.str() == "");

	oss.str("");

	// going to change the log option
	LogOption tmp_option;
	result = get_log_dispatcher().get_option("testlog", tmp_option);
	BOOST_CHECK(result == 0);

	tmp_option.priority = kAll;
	result = get_log_dispatcher().set_option("testlog", tmp_option);
	BOOST_CHECK(result == 0);

	CLOGF(kInfo, "testing");
	// the log is asnyc write to the stream
	sleep(1);
	BOOST_CHECK(oss.str() == "testing\n");

	get_log_dispatcher().clear();
}
